package com.zhangdi.dwperms.token;

import com.zhangdi.dwperms.commons.Contents;
import com.zhangdi.dwtools.security.AESUtils;
import com.zhangdi.dwtools.text.JsonUtil;
import com.zhangdi.dwtools.text.StringUtils;

import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class TokenUtils extends AESUtils {
    public String pojo2base64(AuthToken token) {
        return JsonUtil.obj2json(token);
    }

    public String getAccessToken(String id) {
        long now = new Date().getTime();
        MSToken msToken = new MSToken();
        msToken.setPrincipal(id).setIssuedAt(now).setExpiration(now + Contents.EXPIRE_TIME);
        return super.Encrypt(this.pojo2base64(msToken));
    }

    public String refreshAccessToken(AuthToken token) {
        MSToken msToken = (MSToken) token;
        msToken.setExpiration(new Date().getTime() + Contents.EXPIRE_TIME);
        return this.encrypt(msToken);
    }

    public String encrypt(AuthToken token) {
        return super.Encrypt(this.pojo2base64(token));
    }

    public MSToken decrypt(String encoded) {
        String base64 = super.Decrypt(encoded);
        if (StringUtils.isBlank(base64)) {
            return null;
        }
//        byte[] ordinalBytes = new byte[0];
//        try {
//            ordinalBytes = Encoder.decode (base64);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        MSToken msToken = JsonUtil.json2pojo(base64, MSToken.class);
        msToken.setCredentials(this.encrypt(msToken));

        return msToken;
    }

    public static boolean isExpired(long timestamp) {
        return timestamp <= new Date().getTime();
    }

    public static boolean isExpired(Date time) {
        return time.before(new Date());
    }

    public static long getRefreshTimestamp(AuthToken msToken) {
        return msToken.issuedAt().getTime() + Contents.REFRESH_TIME;
    }
}
